package com.usian.admin.gateway.filter;

import com.usian.jwt.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class AdminGatewayFilter implements GlobalFilter, Ordered {
    /**
     *
     * @param exchange  交换机
     * @param chain 过滤链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        if (path.contains("/login/in") || path.contains("/login/register")) return chain.filter(exchange);
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (StringUtils.isBlank(token)){//是否携带token进行访问
            String json = "{\"errorMsg\":\"token is invalid\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i == 0 || i == -1){//token在有效期内
            String id = claimsBody.get("id")+"";//从载荷中获取用户id
            request = request.mutate().header("userId",id).build();//将用户id存入请求对象
            exchange.mutate().request(request).build();//将改变后的请求对象重新交给交换机
        }
        return chain.filter(exchange);
    }

    //确保过滤器的执行顺序，返回值越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
